import store from '@/store';
import { router } from '@/router'
import { debounce, showMessage } from './utils';
import global from '@/common/global';

const ROUTER_HISTORY = 'myRouterHistory';
const wait = delay => new Promise(r => setTimeout(r, delay))

const noCachePage = [
    '/pages/home/home',
    '/pages/home/startCome',
    '/pages/home/my',
    '/pagesA/mySet/perfectReal',
    '/pagesA/medicalCardMan/addMedical',
    '/pages/login/login',
    '/pagesA/medicalCardMan/medicalCardMan',
    '/pagesA/medicalCardMan/sign' // 省人民免密支付签约
]

const pagesAdmin = global.pagesAdmin || {
    // 核酸开单
    '/pagesA/hospitalCare/selPro': {
        login: true,
        patient: true
    },
    '/pagesA/clinicPay/clinicPayDetail': {
        login: true,
        patient: true
    },
    '/pages/serviceCenter/serviceCenter-wei': {
        patient: true,
        login: true,
    },
    '/pagesB/healthRecords/chooseMedical': {
        login: true,
        patient: true
    },
    '/pagesA/MyRegistration/chooseType': {
        login: true,
        patient: true
    },
    '/pagesB/reportQuery/reportQuery': {
        login: true,
        patient: true
    },
    '/pagesA/hospitalCare/hsjcsq': {
        login: true,
        patient: true
    },
    // 门诊缴费s
    '/pagesA/clinicPay/clinicPay': {
        login: true,
        patient: true
    },
    // 住院中心
    '/pagesA/hospitalCare/hospitalCare': {
        login: true,
        patient: true
    },
    // 我的挂号
    '/pagesA/MyRegistration/MyRegistration': {
        login: true,
        patient: true
    },
    // 产检套餐充值
    '/pagesC/frozenEmbryo/lvfRecord': {
        login: true,
        patient: true
    },
    // 胚胎冷冻
    '/pagesC/frozenEmbryo/apply': {
        login: true,
        patient: true
    },
    '/pagesA/medicalCard/medicalCard': {
        login: true,
        patient: true
    },
    '/pagesA/MyRegistration/RegConfirm': {
        login: true,
        patient: true
    },
    '/pagesA/MyRegistration/ChooseTime': {
        login: true,
        patient: true
    },
    '/pagesA/MyRegistration/DoctorDetails': {
        login: true,
        patient: true
    },
}

/*
    完善  /pagesA/mySet/perfectReal
 */

// 可以在有 router-his 情况下继续通行， 下一页面继续 router-his
const personAdditional = [
    '/pagesA/mySet/perfectReal', // 完善
    '/pagesA/medicalCardMan/addMedical', //新增就诊人
    '/pagesA/medicalCardMan/addOldMedical', // 信息少的新增就诊人
    '/pages/login/login',
    '/pages/home/my'
]

let pagesAdminKeys = []
let patientAdminKeys = []

const initPageAdmin = function() {
    pagesAdminKeys = Object.keys(pagesAdmin);
    patientAdminKeys = pagesAdminKeys.filter(key => {
        const item = pagesAdmin[key];
        return item.patient
    })
}

initPageAdmin()

const isLogin = () => !!uni.getStorageSync('token').accessToken;
export const isCachePage = () => !!uni.getStorageSync(ROUTER_HISTORY);

// 加个防抖， 妈妈再也不怕我陷入死循环了
export const cacheRouter = debounce(function(route) {
    const currentRoute = route || router.currentRoute;
    if (noCachePage.includes(currentRoute.path)) {
        return
    }

    uni.setStorageSync(ROUTER_HISTORY, currentRoute)
}, 500)



export const checkRouter = function({ router, next, to, from }, type) {
}

// 确认登陆过 ？
export const checkToken = async function(self) {
    await new Promise(async (r) => {
        if (!isLogin()) {
            cacheRouter();
            await wait(800)
            self.$Router.replaceAll({
                path: '/pages/home/my',
                query: {
                    mymsg: 'isback',
                    routeUrl: self.$Route.path,
                    ...self.$Route.query
                }
            })
            return
        } else {
            r();
        }
    })
}

// 确认有就诊人 ？
export const checkPatient = async function(self) {
    await checkToken(self);

    const patList = store.state.bussiness.patCardList;

    if (!(patList && patList.length)) {
        if (uni.getStorageSync('userInfo').herenId) { //是否是否有herenId
            cacheRouter()
            self.$Router.push({
                path: '/pagesA/medicalCardMan/addMedical',
            })
        } else {
            self.$Router.push({
                path: '/pagesA/mySet/perfectReal',
                NAVTYPE: 'push'
            })
        }
    }
}


const goAddPersonPage = next => {
    if (global.SYS_CODE === '1001017') {
        next({
            path: '/pagesA/medicalCardMan/addOldMedical',
        })
    } else {
        next({
            path: '/pagesA/medicalCardMan/addMedical',
        })
    }
}

const routerCheckLogin = function(to, from, next) {
    if (!isLogin()) {
        cacheRouter(to);
        setTimeout(() => {
            // #ifdef H5
            window.location.href = uni.getStorageSync('loginUrl') //正式
            // #endif
            // #ifndef H5
            next({
                path: '/pages/home/my'
            })
            // #endif
        }, 500);


        return true
    }
}

const routerCheckPatient = function(to, from, next) {
    if (!routerCheckLogin(to, from, next)) {
        const patList = store.state.bussiness.patCardList;
        if (!(patList && patList.length)) {
            if (uni.getStorageSync('userInfo').herenId) { //是否是否有herenId
                cacheRouter(to)
                goAddPersonPage(next)
            } else {
                cacheRouter(to)
                next({
                    path: '/pagesA/mySet/perfectReal',
                    NAVTYPE: 'push'
                })
            }

            return true
        }
    }
}

const routerHookCheckHistory = function(next, to, from) {
    const hisRouter = uni.getStorageSync(ROUTER_HISTORY);
    const goHis = (his) => {
        uni.setStorageSync(ROUTER_HISTORY, '');
        const routeArg = {
            path: his.path,
            query: his.query,
            NAVTYPE: 'replace'
        }

        setTimeout(() => {
            next(routeArg)
        }, 1000);
    }

    if (hisRouter) {
        if (pagesAdminKeys.includes(hisRouter.path)) {
            const { patient, login } = pagesAdmin[hisRouter.path];
            if (patient) {
                const patList = store.state.bussiness.patCardList;
                if (patList.length) {
                    goHis(hisRouter);
                    return true
                }

            } else if (login) {
                goHis(hisRouter)
                return true
            }
        } else {
            goHis(hisRouter);
            return true
        }

    }
}


// 返回 true 代表 router.js 前置路由不执行后面的
export const myRouteHook = function(to, from, next) {
    // debugger
    const aLog = {
        from,
        to,
        name: 'cqc',
        pagesAdminKeys,
        pagesAdmin,
        ROUTER_HISTORY: uni.getStorageSync(ROUTER_HISTORY)
    }

    console.log(aLog);


    const aIsGoStartHome = isGoStartHome(next, to);
    if (aIsGoStartHome) {
        return true
    }

    if (pagesAdminKeys.includes(to.path)) {
        const { login, patient } = pagesAdmin[to.path];

        if (login) {
            if (routerCheckLogin(to, from, next)) {
                console.log('####未登录');
                return true
            }
        }

        if (patient) {
            if (routerCheckPatient(to, from, next)) {
                console.log('####无就诊人');
                return true
            }
        }
    }


    // #ifdef H5
    if (['/pages/login/login'].includes(from.path)) {
        const { path } = to;

        if (!personAdditional.includes(path) && isLogin()) {
            const pageConfig = pagesAdmin[to];

            if (pageConfig) {
                const { patient } = pageConfig;
                if (patient) {
                    const patList = store.state.bussiness.patCardList;
                    if (!(patList && patList.length)) {
                        if (uni.getStorageSync('userInfo').herenId) {
                            goAddPersonPage(next)
                        } else {
                            next({
                                path: '/pagesA/mySet/perfectReal',
                            })
                        }
                    }

                }
            }
        }
    }
    // #endif

    // 完善等 逻辑前面做过了
    if (personAdditional.includes(from.path) && isLogin()) {
        if (!noCachePage.includes(to.path)) {
            if (routerHookCheckHistory(next, to, from)) {
                return true
            }
        }

    }



    // 从startHome 回来(目测不执行..)
    if (to.path === '/pages/home/home') {
        if (routerHookCheckHistory(next, to, from)) {
            return true
        }
    }

    // console.log('顺利跳转------');
}


export const isGoStartHome = debounce(function(next, to) {
    if (isLogin()) {
        // #ifdef MP-WEIXIN
        // 拿 h5code
        const h5Openid = uni.getStorageSync('h5Openid');
        if (!h5Openid && !['/pagesA/mySet/perfectReal', '/pages/home/startCome', '/pages/home/home'].includes(to.path) && patientAdminKeys.includes(to.path)) { //没授权已经登录 去欢迎页
            cacheRouter(to);
            setTimeout(() => {
                next({
                    path: '/pages/home/startCome',
                    NAVTYPE: 'push'
                })
            }, 500);

            return true
        }
        // #endif


        // 完善
        if (!uni.getStorageSync('userInfo').herenId && patientAdminKeys.includes(to.path)) {
            // if (!uni.getStorageSync('userInfo').herenId && !noCachePage.includes(to.path)) {
            cacheRouter(to);
            next({
                path: '/pagesA/mySet/perfectReal',
                NAVTYPE: 'push'
            })

            return true
        }
    }
}, 500)

export const myRouteHookAfter = function(to, from) {
    const hisRouter = uni.getStorageSync(ROUTER_HISTORY);
    if (hisRouter && to.path === '/pages/home/my' && !isLogin()) {
        showMessage('未登录，请先登录')
    }
}